//
//  YLCSendTrainViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/3/20.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCSendTrainViewController.h"
#import "YLCTitleFieldCell.h"
#import "YLCTrainTimeCell.h"
#import "YLCSelectCell.h"
#import "YLCSubFieldCell.h"
#import "YLCInputInfoCell.h"
#import "YLCTrainPhotoAddCell.h"
#import "YLCProgramSelectModel.h"
#import "YLCAreaModel.h"
#import "ImagePicker.h"
#import "YLCPickModel.h"
#define TITLE_FIELD  @"YLCTitleFieldCell"
#define TRAIN_TIME   @"YLCTrainTimeCell"
#define SELECT_CELL  @"YLCSelectCell"
#define SUB_FIELD    @"YLCSubFieldCell"
#define INPUT_CELL   @"YLCInputInfoCell"
#define PHOTO_ADD    @"YLCTrainPhotoAddCell"
@interface YLCSendTrainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,YLCTrainTimeCellDelegate,YLCTitleFieldCellDelegate,YLCSubFieldCellDelegate,UIActionSheetDelegate,YLCInputInfoCellDelegate>

@end

@implementation YLCSendTrainViewController
{
    UICollectionView *trainTable;
    NSArray *dataList;
    YLCAreaModel *areaModel;
    NSString *starTime;
    NSString *endTimeString;
    UIImage *actionImage;
    NSArray *typeList;
    NSString *typeId;
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"发布" titleColor:[UIColor whiteColor] selector:@selector(sendJob) target:self];
}
//- (UIBarButtonItem*)rightBarButtonItem{
//
//    UIView *barView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 90, 40)];

//    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    backBtn.frame = CGRectMake(5, 0, 50, 40);
//    backBtn.titleLabel.font = [UIFont systemFontOfSize:16];
//    [backBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
//    [backBtn addTarget:self action:@selector(showPreview) forControlEvents:UIControlEventTouchUpInside];
//    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//    [backBtn setTitle:@"预览" forState:UIControlStateNormal];
//    [barView addSubview:backBtn];
    
//    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    closeBtn.frame = CGRectMake(backBtn.frameMaxY+10, 0, 35, 40);
//    closeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
//    [closeBtn addTarget:self action:@selector(sendJob) forControlEvents:UIControlEventTouchUpInside];
//    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
//    [closeBtn setTitle:@"发布" forState:UIControlStateNormal];
//    [barView addSubview:closeBtn];
//
//    return [[UIBarButtonItem alloc]initWithCustomView:barView];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initDataSource];
    [self createCustomView];
}
- (void)initDataSource{
    NSMutableArray *container = [NSMutableArray arrayWithCapacity:0];
    
    NSArray *titleList = @[@"主题",@"",@"时间",@"地区",@"详细地址",@"",@"类型",@"费用",@"联系人",@"联系人电话"];
    
    NSArray *placeholderList = @[@"活动主题",@"",@"",@"请选择",@"请输入详细地址",@"请输入活动详情",@"请选择",@"请输入费用(元)",@"请输入联系人",@"请输入联系人电话"];
    
    for (int i = 0; i<titleList.count; i++) {
        YLCProgramSelectModel *model = [[YLCProgramSelectModel alloc] init];
        
        model.title = titleList[i];
        
        model.placeholder = placeholderList[i];
        
        [container addObject:model];
    }
    dataList = [container copy];
    
    if (_sendType==ActivitySendType) {
        return;
    }
    
    [YLCNetWorking loadNetServiceWithParam:@{} method:@"POST" urlPath:@"app/train/typeLists" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        typeList = responseObject;
        
    }];
}
- (void)createCustomView{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 0.5;
    
    trainTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    trainTable.backgroundColor = RGB(235, 235, 235);
    
    [trainTable registerClass:[YLCTitleFieldCell class] forCellWithReuseIdentifier:TITLE_FIELD];
    
    [trainTable registerClass:[YLCTrainTimeCell class] forCellWithReuseIdentifier:TRAIN_TIME];
    
    [trainTable registerClass:[YLCSelectCell class] forCellWithReuseIdentifier:SELECT_CELL];
    
    [trainTable registerClass:[YLCSubFieldCell class] forCellWithReuseIdentifier:SUB_FIELD];
    
    [trainTable registerClass:[YLCInputInfoCell class] forCellWithReuseIdentifier:INPUT_CELL];
    
    [trainTable registerClass:[YLCTrainPhotoAddCell class] forCellWithReuseIdentifier:PHOTO_ADD];
    
    trainTable.delegate = self;
    
    trainTable.dataSource = self;
    
    [self.view addSubview:trainTable];
    
    [trainTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return dataList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YLCProgramSelectModel *model = dataList[indexPath.row];
    
    if (indexPath.row==0) {
        YLCTitleFieldCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:TITLE_FIELD forIndexPath:indexPath];
        
        cell.delegate = self;
        
        cell.titleField.text = model.subString;
        
        cell.titleField.placeholder = model.placeholder;
        
        return cell;
    }
    if (indexPath.row==1) {
        YLCTrainPhotoAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:PHOTO_ADD forIndexPath:indexPath];
        
        cell.image = actionImage;
        
        return cell;
    }
    if (indexPath.row==2) {
        YLCTrainTimeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:TRAIN_TIME forIndexPath:indexPath];
        
//        cell.beganTimeField.text = starTime;
//        
//        cell.endTimeField.text = endTimeString;
        
        cell.delegate = self;
        
        return cell;
    }
    if (indexPath.row==5) {
        YLCInputInfoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:INPUT_CELL forIndexPath:indexPath];
        
        cell.placeholder = model.placeholder;
        
        cell.text = model.subString;
        
        cell.delegate = self;
        
        return cell;
    }
    if (indexPath.row==3||indexPath.row==6) {
        YLCSelectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SELECT_CELL forIndexPath:indexPath];
        
        if (indexPath.row==6&&_sendType==ActivitySendType) {
            cell.needHidden = YES;
        }else{
            cell.needHidden = NO;
            
            cell.title = model.title;
            
            cell.titleColor = RGB(133,139,141);
            
            cell.subString = [YLCFactory isStringOk:model.subString]?model.subString:model.placeholder;
            
            cell.subColor = [YLCFactory isStringOk:model.subString]?RGB(71, 73, 74):RGB(201,209,212);
            
            cell.backgroundColor = [UIColor whiteColor];
        }
        return cell;
    }
    
    YLCSubFieldCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:SUB_FIELD forIndexPath:indexPath];
    
    cell.model = model;
    
    cell.delegate = self;
    
    cell.subField.text =  model.subString;
    
    cell.index = indexPath.row;
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==1) {
        return CGSizeMake(self.view.frameWidth, 200);
    }
    if (indexPath.row==5) {
        return CGSizeMake(self.view.frameWidth, 150);
    }
    if (_sendType==ActivitySendType&&indexPath.row==6) {
        return CGSizeZero;
    }
    return CGSizeMake(self.view.frameWidth, 60);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==3) {
        [self showAreaList];
    }
    if (indexPath.row==1) {
        [self showImageSheet];
    }
    if (indexPath.row==6) {
        [self showTypePickList];
    }
}
- (void)showImageSheet{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
    
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    [[ImagePicker sharedManager] dwSetPresentDelegateVC:self SheetShowInView:self InfoDictionaryKeys:buttonIndex];
    
    //回调
    [[ImagePicker sharedManager] dwGetpickerTypeStr:^(NSString *pickerTypeStr) {
        
        
        
    } pickerImagePic:^(UIImage *pickerImagePic) {
        UIImage *image = [pickerImagePic  ccc_resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:CGSizeMake(400, 300) interpolationQuality:kCGInterpolationDefault];
        
        if (image) {
            actionImage = image;
        }else{
            actionImage = pickerImagePic;
        }
        [trainTable reloadData];
    }];
    
}
- (void)showTypePickList{
    if (JK_IS_ARRAY_NIL(typeList)) {
        [SVProgressHUD showErrorWithStatus:@"列表尚未加载成功，请稍后"];
        return;
    }
    NSMutableArray *container = [NSMutableArray arrayWithCapacity:0];
    
    for (NSDictionary *dict in typeList) {
        [container addObject:dict[@"name"]];
    }
    YLCPickModel *pickModel = [[YLCPickModel alloc] init];
    pickModel.rowArr = container.copy;
    pickModel.selectIndex = 0;
    RACSubject *signal = [RACSubject subject];
    [YLCHUDShow showPickerListWithList:@[pickModel] signal:signal];
    [signal subscribeNext:^(id x) {
        YLCPickModel *model = x[0];
        NSDictionary *selectDict = typeList[model.selectIndex];
        [self changeDataListWithText:selectDict[@"name"] index:6 isReload:YES];
        typeId = selectDict[@"id"];
    }];
}
- (void)showAreaList{
    RACSubject *areaSignal = [RACSubject subject];
    [YLCHUDShow showAreaPickWithSignal:areaSignal];
    [areaSignal subscribeNext:^(id x) {
        areaModel =  x;
        [self changeDataListWithText:areaModel.areaname index:3 isReload:YES];
    }];
}
- (void)changeDataListWithText:(NSString *)text
                         index:(NSInteger)index
                      isReload:(BOOL)isReload{
    NSMutableArray *container = [dataList mutableCopy];
    YLCProgramSelectModel *model = dataList[index];
    model.subString = text;
    [container setObject:model atIndexedSubscript:index];
    dataList = container.copy;
    if (isReload) {
        [trainTable reloadData];
    }
}
#pragma mark - CellDelegate
- (void)titleDidChangeWithTitle:(NSString *)title{
    [self changeDataListWithText:title index:0 isReload:NO];
}
- (void)beganTimeDidChangeWithBeganTime:(NSString *)beganTime{
    starTime = beganTime;
}
- (void)endTimeDidChangeWithEndTime:(NSString *)endTime{
    endTimeString = endTime;
}
- (void)subDidchangeWithTxt:(NSString *)text index:(NSInteger)index{
    [self changeDataListWithText:text index:index isReload:NO];
}
- (void)didInfoChangedWithText:(NSString *)text{
    [self changeDataListWithText:text index:5 isReload:NO];
}
- (void)showPreview{
    
}
- (void)sendJob{
    if (!actionImage) {
        [SVProgressHUD showErrorWithStatus:@"请选择海报照片"];
        return;
    }
    YLCProgramSelectModel *titleModel = dataList[0];
    if (JK_IS_STR_NIL(titleModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入活动主题"];
        return;
    }
    if (_sendType==TrainSendType) {
        [self sendTrain];
    }else{
        [self sendActivity];
    }

}
- (void)sendTrain{
    YLCProgramSelectModel *titleModel = dataList[0];
    YLCProgramSelectModel *placeModel = dataList[4];
    YLCProgramSelectModel *feeModel = dataList[7];
    YLCProgramSelectModel *typeModel = dataList[6];
    YLCProgramSelectModel *contactUserModel = dataList[8];
    YLCProgramSelectModel *contactPhoneModel = dataList[9];
    YLCProgramSelectModel *infoModel = dataList[5];
    if (JK_IS_STR_NIL(titleModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入主题活动"];
        return;
    }
    if (JK_IS_STR_NIL(starTime)) {
        [SVProgressHUD showErrorWithStatus:@"请输入开始时间"];
        return;
    }
    if (JK_IS_STR_NIL(endTimeString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入结束时间"];
        return;
    }
    if (JK_IS_STR_NIL(areaModel.id)) {
        [SVProgressHUD showErrorWithStatus:@"请选择地址"];
        return;
    }
    if (JK_IS_STR_NIL(placeModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入详细地址"];
        return;
    }
    if (JK_IS_STR_NIL(feeModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入活动费用"];
        return;
    }
    if (JK_IS_STR_NIL(typeModel.subString)) {
        typeModel.subString = @"";
    }
    if (JK_IS_STR_NIL(contactUserModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入联系人姓名"];
        return;
    }
    
    if (JK_IS_STR_NIL(contactUserModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入联系人姓名"];
        return;
    }
    
    
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    NSString *imageString = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",[actionImage allBase64String]];
    [YLCNetWorking loadNetServiceWithParam:@{@"token":userModel.token,@"userId":userModel.user_id,@"title":titleModel.subString,@"beginTime":starTime,@"endTime":endTimeString,@"locationId":areaModel.id,@"place":placeModel.subString,@"fee":feeModel.subString,@"type":typeModel.subString,@"contactUser":contactUserModel.subString,@"contact":contactPhoneModel.subString,@"poster":imageString,@"content":infoModel.subString} method:@"POST" urlPath:@"app/train/doSave" delegate:self response:^(id responseObject, NSError *error) {
        
        if (error) {
            
            return ;
            
        }
        
        [SVProgressHUD showSuccessWithStatus:@"发布成功！"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
- (void)sendActivity{
    YLCProgramSelectModel *titleModel = dataList[0];
    YLCProgramSelectModel *placeModel = dataList[4];
    YLCProgramSelectModel *feeModel = dataList[7];
    YLCProgramSelectModel *typeModel = dataList[6];
    YLCProgramSelectModel *contactUserModel = dataList[8];
    YLCProgramSelectModel *contactPhoneModel = dataList[9];
    YLCProgramSelectModel *infoModel = dataList[5];
    if (JK_IS_STR_NIL(titleModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入主题活动"];
        return;
    }
    if (JK_IS_STR_NIL(starTime)) {
        [SVProgressHUD showErrorWithStatus:@"请输入开始时间"];
        return;
    }
    if (JK_IS_STR_NIL(endTimeString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入结束时间"];
        return;
    }
    if (JK_IS_STR_NIL(areaModel.id)) {
        [SVProgressHUD showErrorWithStatus:@"请选择地址"];
        return;
    }
    if (JK_IS_STR_NIL(placeModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入详细地址"];
        return;
    }
    if (JK_IS_STR_NIL(feeModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入活动费用"];
        return;
    }
    if (JK_IS_STR_NIL(typeModel.subString)) {
        typeModel.subString = @"";
    }
    if (JK_IS_STR_NIL(contactUserModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入联系人姓名"];
        return;
    }
    
    if (JK_IS_STR_NIL(contactUserModel.subString)) {
        [SVProgressHUD showErrorWithStatus:@"请输入联系人姓名"];
        return;
    }

    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    NSString *imageString = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",[actionImage allBase64String]];
    [YLCNetWorking loadNetServiceWithParam:@{@"token":userModel.token,@"userId":userModel.user_id,@"title":titleModel.subString,@"beginTime":starTime,@"endTime":endTimeString,@"locationId":areaModel.id,@"place":placeModel.subString,@"fee":feeModel.subString,@"type":typeModel.subString,@"contactName":contactUserModel.subString,@"contact":contactPhoneModel.subString,@"poster":imageString,@"content":infoModel.subString,@"status":@"0"} method:@"POST" urlPath:@"app/activity/doSave" delegate:self response:^(id responseObject, NSError *error) {
        
        if (error) {
            
            return ;
            
        }
        
        [SVProgressHUD showSuccessWithStatus:@"发布成功！"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
- (NSString *)title{
    if (_sendType==TrainSendType) {
        return @"培训";
    }else{
        return @"活动";
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
